<!--
 * @Author: wanglianxin
 * @Date: 2022-08-23 18:48:02
 * @LastEditors: wanglianxin
 * @LastEditTime: 2023-05-09 17:12:07
 * @FilePath: \standard-check\src\components\Authorization\index.vue
 * @Description: 授权组件
-->
<template>
  <a-modal
    title="授权"
    v-model="isVisible"
    @cancel="handleCancel"
    @ok="handleOk"
    :width="376"
    :maskClosable="false"
    :destroyOnClose="true"
    class="auth-modal"
  >
    <a-form
      :form="form"
      autocomplete="off"
      labelAlign="right"
      @submit="handleSubmit"
      :labelCol="labelCol"
      :wrapperCol="wrapperCol"
      :colon="false"
    >
      <a-form-item label="授权柜员号">
        <a-input v-show="false"></a-input>
        <a-input
          v-decorator="[
            'clkno',
            {
              initialValue: '',
              rules: [
                { required: true, message: '请输入授权柜员号' },
                {
                  pattern: '^[^\u4e00-\u9fa5]{1,}$',
                  message: '柜员号格式不正确,不允许有中文',
                },
              ],
            },
          ]"
        ></a-input>
      </a-form-item>
      <a-form-item label="指纹与密码" v-if="switchAuthTypeVisible">
        <a-select @change="switchAuthType" default-value="2">
          <a-select-option value="2">---请选择---</a-select-option>
          <a-select-option value="1">指纹</a-select-option>
          <a-select-option value="0">密码</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="柜员密码" v-if="current == 0">
        <a-input
          v-if="browser != 'ie'"
          class="pwd"
          autocomplete="off"
          type="text"
          @change="handleInputChange($event)"
          v-decorator="[
            //'passwd',
            'clkpwd',
            {
              initialValue: '',
              rules: [
                { required: true, message: '请输入柜员密码' },
                {
                  pattern: '^[^\u4e00-\u9fa5]{6}$',
                  message: '密码请控制在6位非中文字符',
                },
              ],
            },
          ]"
        ></a-input>
        <a-input
          v-else
          autocomplete="off"
          type="password"
          v-decorator="[
            //'passwd',
            'clkpwd',
            {
              initialValue: '',
              rules: [
                { required: true, message: '请输入柜员密码' },
                {
                  pattern: '^[^\u4e00-\u9fa5]{6}$',
                  message: '密码请控制在6位非中文字符',
                },
              ],
            },
          ]"
        ></a-input>
      </a-form-item>
    </a-form>
    <div class="modal-content">
      <div v-if="current == 1">
        <div class="fingerprint" :class="{ pass: pass }"></div>
        <p v-if="showReload">
          <a-button key="back" @click="reloadFinger">重新录入指纹</a-button>
        </p>
        <p v-else>
          <span v-if="!pass">请录入指纹</span>
          <span v-else>录入指纹成功</span>
        </p>
      </div>
    </div>
    <template slot="footer">
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" @click="handleOk">确定</a-button>
    </template>
  </a-modal>
</template>
<script>
import Crypto from '../../utils/crypto';
import { accredit } from '../../api/index';
import Fingerprint from './Fingerprint.vue';
export default {
  mixins: [Fingerprint],
  props: ['visibled'],
  data() {
    return {
      form: this.$form.createForm(this, { name: 'form' }), //表单实例
      haveFinger: true, //有指纹驱动
      visibleModal: false, //组件弹窗开关
      current: '2', //当前授权类型    0密码  1指纹 2请选择
      wrapperCol: {
        span: 15,
      },
      labelCol: {
        span: 7,
      },
      labelAlign: 'left',
      formData: {
        layout: 'horizontal',
      },
      formModel: [], //表单数据
      pass: false, //授权是否通过
      showReload: false, //是否显示重录
      password: '', //指纹、密码
      browser: 'chrome', //浏览器类型
      switchAuthTypeVisible: false, //切换授权类型 显示开关 默认false不显示
      isVisible: false,
    };
  },
  computed: {},
  async mounted() {
    if (!!window.ActiveXObject || 'ActiveXObject' in window) {
      this.browser = 'ie';
    } else {
    }
    //默认账号密码
    this.initAuth();
  },
  methods: {
    initAuth() {
      let authorize = this.$config.authorize;
      if (!authorize || !authorize.length) {
        //如果没有配置默认两种授权方式
        authorize = [0, 1];
      }
      if (authorize.includes(0) && authorize.includes(1)) {
        this.switchAuthTypeVisible = true;
        this.switchAuthType(2);
      } else if (authorize.includes(0)) {
        this.switchAuthType(0);
      } else if (authorize.includes(1)) {
        this.switchAuthType(1);
      }
    },
    /**
     * @description: 密码限制6位
     * @param {*} e event
     * @return {*}
     */
    handleInputChange(e) {
      if (e.target.value.length > 6) {
        this.$nextTick(() => {
          this.form.setFieldsValue({ passwd: e.target.value.substring(0, 6) });
          this.form.validateFields(['passwd']);
        });
      }
    },
    /**
     * @description: 切换授权方式
     * @param {*} type 0指纹  1密码 2请选择
     * @return {*}
     */
    async switchAuthType(type) {
      this.resetForm();
      this.current = type;
      if (type == '1') {
        //指纹授权
        try {
          if (this.browser == 'ie') {
            this.startIeFinger();
          } else {
            try {
              await this.initWs();
            } catch (err) {
              this.autoPass();
              return;
            }
            this.startFinger();
          }
          console.log('可以指纹');
        } catch (err) {
          console.log('指纹采集控件未找到，请检查', err);
          this.autoPass();
          return;
        }
      } else if (type == '0') {
        // 密码授权
        this.closeWs();
        //获取机构
      } else {
        this.resetForm();
      }
    },
    /**
     * @description: 测试阶段当未识别到指纹控件时 自动通过
     * @return {*}
     */
    autoPass() {
      this.haveFinger = false;
      this.$modalMessage.warning('未识别到指纹控件，请安装');
    },
    /**
     * @description: 重置表单
     * @return {*}
     */
    resetForm() {
      if (this.current == 0) {
        //指纹
        this.form.resetFields(['passwd']);
        if (this.password) {
          this.showReload = true;
          this.pass = false;
          this.password = '';
        } else {
          this.showReload = false;
          this.pass = false;
        }
        this.closeWs();
      } else {
        //密码
        this.form.resetFields(['passwd']);
      }
    },
    /**
     * @description: 通过
     * @return {*}
     */
    handleOk() {
      if (this.current == 0) {
        //账号密码模式
        let status = this.handleSubmit();
        if (status) {
          let values = this.getFormValue();
          this.reqAccredit({ ...values }).then(
            (data) => {
              this.$store.commit('business/current-auth-clkno', values.clkno);
              this.$emit('onOk');
              this.visibleModal = false;
              this.$emit('update:visibled', false);
            },
            (err) => {
              console.log('授权失败,重新填写');
              this.resetForm();
            }
          );
        }
      } else if (this.current == 1) {
        // 指纹
        let status = this.handleSubmit();
        if (status) {
          let values = this.getFormValue();
          let clkno = values.clkno;
          if (!this.password) {
            this.showReload = true;
            this.pass = false;
            this.$modalMessage.warning('请录入指纹');
            return;
          }
          this.reqAccredit({ clkno, passwd: this.password, depno: '', safvalue: 0 }).then(
            (data) => {
              if (data.code == '200') {
                this.$store.commit('business/current-auth-clkno', values.clkno);
                this.$emit('onOk');
                this.visibleModal = false;
                this.$emit('update:visibled', false);
                this.closeWs();
              } else {
                this.$modalMessage.warning('授权失败，请重新尝试');
                this.resetForm();
              }
            },
            (err) => {
              this.resetForm();
            }
          );
          return;
        }
      } else {
        this.$modalMessage.warning('请选择授权方式');
      }
    },
    /**
     * @description: 取消
     * @return {*}
     */
    handleCancel() {
      this.$store.commit('business/current-auth-clkno', null);
      this.$emit('onCancel');
      this.visibleModal = false;
      this.$emit('update:visibled', false);
      this.closeWs();
    },
    /**
     * @description: 请求授权
     * @return {*}
     */
    reqAccredit(reqData) {
      return accredit({ ...reqData, clkpwd: Crypto.encrypt(reqData.clkpwd) });
      //return accredit({ ...reqData, tradeCode: '181107' });
    },
    /**
     * @description: 开始ie浏览器指纹
     * @return {*}
     */
    startIeFinger() {
      var dwWaitTime = 18000; // 超时EDIT
      var nRet = -1;
      // TESO

      // 0x30 拆分格式
      ObjFinger.nSucStrFmtTyp = 1;
      // 商行协议
      ObjFinger.nComProtocol = 2;
      // USB协议
      ObjFinger.nUsbProtocol = 0;
      // 是否检测抬起
      //ObjFinger.nRegChkToLv = 1;
      // 是否显示 注册指纹模板时的对话框
      ObjFinger.nRegShowDlg = 1;
      // 是否显示 验证指纹特征时的对话框
      ObjFinger.nVerShowDlg = 1;
      // 是否禁用自动提速  0-启用自动提速， 4=固定9600波特率
      ObjFinger.nNotSpeedUp = 0;
      //ObjFinger.nComShwOnOcx = 10;

      // 通用方法
      // 验证特征，Base64
      nRet = ObjFinger.FPIGetFeature(0, dwWaitTime);
      if (nRet) {
        this.showReload = true;
        this.password = '';
        this.$modalMessage.error('验证指纹特征失败。错误码:[' + nRet + ']');
        this.pass = false;
      } else {
        this.showReload = false;
        this.password = ObjFinger.FPIGetFingerInfo();
        this.pass = true;
      }
    },
    /**
     * @description: 开始现代浏览器指纹
     * @return {*}
     */
    startFinger() {
      //先关闭连接
      var port = 0; // 0 表示 USB 口，>0 表示 COM 口
      var timeout = 18;
      this.FPIGetFeature(
        port,
        timeout,
        (feature) => {
          this.showReload = false;
          this.password = feature;
          this.pass = true;
        },
        (code, msg) => {
          this.showReload = true;
          this.password = '';
          this.$modalMessage.error('验证指纹特征失败。错误码:[' + code + ':' + msg + ']');
          this.pass = false;
          this.closeWs();
        }
      );
    },
    /**
     * @description: 重录
     * @return {*}
     */
    async reloadFinger() {
      this.showReload = false;
      if (this.browser == 'ie') {
        this.startIeFinger();
      } else {
        await this.initWs();
        this.startFinger();
      }
    },
    /**
     * @description: 初始化ws连接
     * @return {*}
     */
    initWs() {
      return new Promise((resolve, reject) => {
        this.initParam('ws://localhost:18831');
        this.connect(
          function () {
            // 连接成功
            resolve();
          },
          function (code, msg) {
            reject(msg);
          }
        );
      });
    },
    /**
     * @description: 关闭ws
     * @return {*}
     */
    closeWs() {
      this.disconnect();
    },
    /**
     * @description: 提交触发表单校验
     * @return {*}
     */
    handleSubmit() {
      let status = false;
      this.form.validateFields((err) => {
        status = !err;
      });
      return status;
    },
    /**
     * @description: 获取表单绑定值
     * @return {*}
     */
    getFormValue() {
      return this.form.getFieldsValue();
    },
  },
  watch: {
    visibled: {
      handler(value) {
        this.visibleModal = value;
      },
      immediate: true,
    },
    visibleModal: {
      handler(value) {
        this.isVisible = value;
      },
      immediate: true,
    },
  },
};
</script>
<style lang="stylus" type="text/stylus" rel="stylesheet/stylus">
.auth-modal
  &>>>.account-form .ant-form-item
    margin-bottom 0
  .pwd
    text-security disc
    -webkit-text-security disc
    -mox-text-security disc
  .ant-modal-body
    padding 24px 0
  .modal-content
    // height 250px
    overflow hidden
    .fingerprint
      margin-left 116px
      width 140px
      height 140px
      background url('../../assets/images/fingerprint.png')
      &.pass
        background url('../../assets/images/complete.png')
    p
      text-align center
      color #1890FF
      font-size 14px
  .modal-title
    span
      display inline-block
      line-height 56px
      cursor pointer
      margin-right 32px
      border-bottom 2px solid transparent
      &:hover, &.on
        color #1890FF
        border-bottom-color #1890FF
</style>
